package shiqi.exception;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import shiqi.util.SpringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: ascend
 * @description: 控制类异常统一处理
 * @author: shiqi
 * @create: 2022-03-18 20:54
 **/
@Aspect//声明这是一个切面
@Component//把这个类交给spring管理
public class ControllerExceptionAspect {


    /**
     * @author shiqi
     * @createTime 2022/3/18 21:08
     * @desc 连接点
     * @param
     * @return void
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void exceptionAspect() {

    }

    /**
     * @author shiqi
     * @createTime 2022/3/18 21:17
     * @desc 异常处理
     * @param  joinPoint
     * @param  e
     * @return java.lang.Object
     */
    @AfterThrowing(pointcut = "exceptionAspect()", throwing = "e")
    public Object handleException(JoinPoint joinPoint, Throwable e) throws Throwable {
        HttpServletRequest request = SpringUtils.getCurrentRequest();
        Boolean view = isView(e, request);
        System.out.println(view);
        Object result = null;
        if (view) {
            ModelAndView modelAndView = new ModelAndView("error");//配置需要跳转的Controller方法
            request.setAttribute("message", "系统的转换能力出现异常");
            return modelAndView;
        } else {
            result = "发生错误啦";
        }
        return result;
    }

    //判断是否是页面
    private Boolean isView(Throwable e, HttpServletRequest request) throws Throwable {
        //获取拦截器判断的返回结果类型
        Object o = request.getAttribute("method_return_is_view");
        if (o == null) {
            throw e;
        }
        //是否是html/text
        boolean isView = (Boolean) o;
        return isView;
    }


}
